package com.kqb.auth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kqb.api.auth.bo.UserInfoInTokenBO;
import com.kqb.auth.domain.dto.AuthenticationDTO;
import com.kqb.auth.domain.pojo.AuthAccount;
import com.kqb.auth.service.AuthAccountService;
import com.kqb.common.core.utils.AjaxResult;
import com.kqb.auth.mapper.AuthAccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 杉果树皮
 * @date 2025/4/11 10:19
 * @description:
 */
@Service
public class AuthAccountServiceImpl implements AuthAccountService {

    @Autowired
    AuthAccountMapper authAccountMapper;


    @Override
    public AjaxResult getUserInfoByNameAndPassword(AuthenticationDTO authenticationDTO) {
        // 1. 根据用户名查询用户
        QueryWrapper<AuthAccount> authAccountQueryWrapper = new QueryWrapper<>();
        authAccountQueryWrapper
                .eq("sys_type", authenticationDTO.getSysType())
                .ne("status", -1)
                .eq("username", authenticationDTO.getPrincipal());
        AuthAccount authAccount = authAccountMapper.selectOne(authAccountQueryWrapper);
        if (ObjectUtil.isNull(authAccount)) {
            return AjaxResult.error("用户不存在");
        }
        if (0 == authAccount.getStatus()) {
            return AjaxResult.error("账号已被封禁,请联系管理员");
        }
        // 2. 判断密码是否正确
        if (!SecureUtil.md5(authenticationDTO.getCredentials()).equals(authAccount.getPassword())) {
            return AjaxResult.error("密码错误");
        }
        // 3. 认证成功返回
        UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
        BeanUtil.copyProperties(authAccount, userInfoInTokenBO);
        return AjaxResult.success("登录成功", userInfoInTokenBO);
    }
}
